package com.dcjt.firehotcarpad.fragment

import LocationPool
import MapOperationEventPool
import NewMessagePool
import android.annotation.SuppressLint
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.DividerItemDecoration
import com.amap.api.location.AMapLocation
import com.amap.api.maps.AMapUtils
import com.amap.api.maps.model.LatLng
import com.aries.library.fast.manager.LoggerManager
import com.aries.library.fast.module.fragment.FastRefreshLoadFragment
import com.aries.library.fast.retrofit.FastObserver
import com.aries.library.fast.util.FastStackUtil
import com.aries.library.fast.util.ToastUtil
import com.aries.ui.view.radius.RadiusTextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.dcjt.firehotcarpad.R
import com.dcjt.firehotcarpad.base.BaseViewModelEntity
import com.dcjt.firehotcarpad.entity.BaseEntity
import com.dcjt.firehotcarpad.entity.BaseListEntity
import com.dcjt.firehotcarpad.entity.InstructionListEntity
import com.dcjt.firehotcarpad.helper.CountDownDialogHelper
import com.dcjt.firehotcarpad.manager.DataManager
import com.dcjt.firehotcarpad.model.SendMessageUtils
import com.dcjt.firehotcarpad.moudle.NavActivity
import com.dcjt.firehotcarpad.retrofit1.repository.ApiRepository1
import com.dcjt.firehotcarpad.utils.MarkerToMapType
import com.dcjt.firehotcarpad.utils.MessageUtils
import com.dcjt.firehotcarpad.utils.StringUtils
import com.google.gson.Gson
import com.google.gson.annotations.SerializedName
import java.text.DecimalFormat
import kotlin.math.floor

/**
 * Created by cj on 2021/2/22.
 * Email:codesexy@163.com
 * Function:
 * desc:周边水源列表
 */
class InstructionListFragment : FastRefreshLoadFragment<InstructionListEntity>(),
    BaseQuickAdapter.OnItemChildClickListener,
    NewMessagePool.NewMessageObserverObserver {

    companion object {
        fun newInstance(zqid:String): InstructionListFragment {
            var fragment = InstructionListFragment()
            val bundle = Bundle()
            bundle.putString("zqid", zqid)
            fragment.setArguments(bundle)
            return fragment
        }
    }

    private lateinit var mAdapter: InstructionListAdapter
    private lateinit var mViewModel: InstructionListViewModel

    //之前的位置
    private var preLocation: AMapLocation? = null

    private var prePostTime: Long = 0
    private var zqid: String = ""

    override fun getContentLayout(): Int = R.layout.fast_layout_multi_status_refresh_recycler

    @SuppressLint("UseRequireInsteadOfGet")
    override fun beforeInitView() {
        if (!StringUtils.isEmpty(arguments?.getString("zqid"))){
            zqid = arguments?.getString("zqid").toString()
        }

        super.beforeInitView()
    }
    override fun initView(savedInstanceState: Bundle?) {
        mViewModel = ViewModelProviders.of(this).get(InstructionListViewModel::class.java)
        NewMessagePool.get().registerNewMessageObserver(this)
        mViewModel.listData.observe(
            this,
            Observer<BaseViewModelEntity<List<InstructionListEntity>>> { entity ->
                mEasyStatusView.content()
                if (entity.isSuccess) {
                    val data = entity.data
                    if (data == null || data.isEmpty()) {
                        if (0 == DEFAULT_PAGE && mAdapter.data.size == 0) { //第一页就么有
                            mEasyStatusView.empty()
                        } else {
                            mAdapter.loadMoreEnd()
                        }
                        return@Observer
                    }
                    mAdapter.loadMoreComplete()

                    if (mRefreshLayout.isRefreshing && DEFAULT_PAGE === 0) {
                        mAdapter.setNewData(ArrayList())
                        mRefreshLayout.finishRefresh()
                    }

                    mAdapter.addData(data)

                    if (data.size < DEFAULT_PAGE_SIZE) {
                        mAdapter.loadMoreEnd()
                    }
                } else {//失败
                    if (mRefreshLayout.isRefreshing) {
                        mRefreshLayout.finishRefresh();
                    } else {
                        if (mAdapter.data.size == 0) {
                            mEasyStatusView.error();
                        }
                    }
                }
            })
        //
        mRecyclerView.addItemDecoration(
            DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL)
        )

        mAdapter.onItemChildClickListener = this
    }



    override fun onDestroy() {
        super.onDestroy()
        NewMessagePool.get().unRegisterNewMessageObserver(this)
    }

    override fun loadData(page: Int) {
        prePostTime = System.currentTimeMillis()
        mViewModel.loadData(zqid,page)
    }

    override fun getAdapter(): BaseQuickAdapter<InstructionListEntity, BaseViewHolder> =
        InstructionListAdapter().apply { mAdapter = this }

    override fun onItemChildClick(
        adapter: BaseQuickAdapter<*, *>?,
        clicKView: View?,
        position: Int
    ) {
        var entity = adapter!!.data[position] as InstructionListEntity
//
        when (clicKView!!.id) {
            R.id.container -> {
                NewMessagePool.get().onObserverMessageZl(entity,0)

            }
        }
    }

    override fun onMessageZLnRefresh() {
        super.onMessageZLnRefresh()
        //刷新
        mRefreshLayout.autoRefresh()
    }


}

class InstructionListViewModel : ViewModel() {

    var listData: MutableLiveData<BaseViewModelEntity<List<InstructionListEntity>>> =
        MutableLiveData()

    fun loadData(zqid: String,page: Int) {
        ApiRepository1.getInstance().getInstructionList(zqid, page,"")
            .subscribe(object : FastObserver<BaseListEntity<InstructionListEntity>>() {
                override fun _onNext(entity: BaseListEntity<InstructionListEntity>) {
                    listData.postValue(BaseViewModelEntity(entity.records, true))
                }

                override fun _onError(errorRes: Int, errorCode: Int, e: Throwable) {
                    super._onError(errorRes, errorCode, e)
                    listData.postValue(BaseViewModelEntity(isSuccess = false))
                }
            })
    }

}


//data class InstructionListEntity(
//    @SerializedName("bz")
//    val bz: Any?,
//    @SerializedName("dsfssj")
//    val dsfssj: Any?,
//    @SerializedName("fsdwid")
//    val fsdwid: Any?,
//    @SerializedName("fsdwmc")
//    val fsdwmc: Any?,
//    @SerializedName("fsrid")
//    val fsrid: Any?,
//    @SerializedName("fsrmc")
//    val fsrmc: Any?,
//    @SerializedName("fssj")
//    val fssj: Any?,
//    @SerializedName("id")
//    val id: String?,
//    @SerializedName("is_deleted")
//    val isDeleted: Int?,
//    @SerializedName("jsdwmcj")
//    val jsdwmcj: Any?,
//    @SerializedName("lzlxdm")
//    val lzlxdm: Any?,
//    @SerializedName("sfzyy")
//    val sfzyy: Any?,
//    @SerializedName("zlfj")
//    val zlfj: String?,
//    @SerializedName("zlmc")
//    val zlmc: String?,
//    @SerializedName("zlnr")
//    val zlnr: String?,
//    @SerializedName("zlzt")
//    val zlzt: Int?,
//    @SerializedName("zqid")
//    val zqid: String?
//)

class InstructionListAdapter(private var format: DecimalFormat = DecimalFormat("0.#")) :
    BaseQuickAdapter<InstructionListEntity, BaseViewHolder>(R.layout.item_layout_instruction_list) {

    override fun convert(helper: BaseViewHolder?, item: InstructionListEntity?) {
        helper!!
        item!!
        helper.setText(R.id.tv_name, if (!StringUtils.isEmpty(item.zlmc)) item.zlmc else item.zlnr)
            .setText(R.id.tv_time, item.fssj.toString())
            .setText(R.id.rtv_zt,if (item.dwzlzt?.toInt() == 3) "已签收" else "未签收" )
        var  rtv_zt =  helper.getView<RadiusTextView>(R.id.rtv_zt)
        rtv_zt.isSelected = item.dwzlzt?.toInt() == 3
        helper.addOnClickListener(R.id.container)
    }

}